//
//  YJCalenderView.m
//  Orthopeddic
//
//  Created by apple on 16/4/22.
//  Copyright © 2016年 杨江. All rights reserved.
//

#import "YJCalenderView.h"
#import "YJCalenderCollectionViewCell.h"
#import "Changed.h"
@interface YJCalenderView ()<UICollectionViewDelegate,UICollectionViewDataSource>




@property (nonatomic,strong)UISwipeGestureRecognizer *leftSwipeGesture;
@property (nonatomic,strong)UISwipeGestureRecognizer *rightSwipeGesture;
@property (nonatomic,strong)NSArray *weekdays;
@property (nonatomic,assign)NSInteger monthNumber;
@property (nonatomic,assign)NSInteger dayNumber;
@end


@implementation YJCalenderView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initalizeDataSource];
        [self initalizeView];
    }
    return self;
}

- (void)initalizeDataSource{
//    self.date = [NSDate dateWithTimeIntervalSinceNow: 8 * 3600];
    self.date = [NSDate date];
    self.weekdays = @[@"星期天",@"星期一",@"星期二",@"星期三",@"星期四",@"星期五",@"星期六"];

}

- (void)initalizeView{
    [self addSubview:self.dateLabel];
    [self addSubview:self.collectionView];
    [self addGestureRecognizer:self.leftSwipeGesture];
    [self addGestureRecognizer:self.rightSwipeGesture];
    [self addSubview:self.deleteButton];
    [self addSubview:self.soureButton];
//    [self numberOfMonthToday];
  _monthNumber = [self numberOfMonth];

}

//获得当前月份的第一天是星期几

- (NSInteger)getFirstDayOfMonth:(NSDate *)date{

    NSCalendar *calender = [NSCalendar currentCalendar];
    //得到当前月第一天
    NSDateComponents *compoents = [calender components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:date];
    compoents.day = 1;
    NSDate *firstDay = [calender dateFromComponents:compoents];
    
    NSInteger weekday = [calender ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitWeekOfMonth forDate:firstDay];
    return weekday - 1;
}
//获得当前月的天数
- (NSInteger)numberOfMonthWithData: (NSDate *)date{
    NSCalendar *calender = [NSCalendar currentCalendar];
    
    NSRange range = [calender rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
    
    return range.length;
}

//当前时间的下一个月

- (NSDate *)nextMonth:(NSDate *)date{
    NSDateComponents *components= [[NSDateComponents alloc]init];
    components.month = 1;
  NSDate *nextMonth = [[NSCalendar currentCalendar] dateByAddingComponents:components toDate:date options:NSCalendarWrapComponents];
    return nextMonth;

}
//获取今天是当月第几天
- (NSInteger)numberOfMonthToday{
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"yyyy--MM--dd";
    NSString *dateString = [formatter stringFromDate:self.date];
    NSString *str = [dateString substringFromIndex:10];
   
    return [str integerValue];
}

//获取今天是第几个月
- (NSInteger)numberOfMonth{
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"yyyy--MM--dd";
    NSString *dateString = [formatter stringFromDate:self.date];
    NSString *str = [dateString substringWithRange:NSMakeRange(6, 2)];
    return [str integerValue];
}
//当前时间的上一个月
- (NSDate *)lastMonth:(NSDate *)date{
    NSDateComponents *components= [[NSDateComponents alloc]init];
    components.month = -1;
    NSDate *lastMonth = [[NSCalendar currentCalendar] dateByAddingComponents:components toDate:date options:NSCalendarWrapComponents];
    return lastMonth;
    
}


#pragma mark --  <UICollectionViewDelegate,UICollectionViewDataSource>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{

    return 2;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section == 0) {
        return self.weekdays.count;
    }
    return 42;

}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    YJCalenderCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"YJcell" forIndexPath:indexPath];
    Changed *changed = [Changed defaultSingleton];
    
    
    if (indexPath.section == 0) {
        cell.dateLabel.text = self.weekdays[indexPath.row];
        cell.backgroundColor = [UIColor blueColor];
        cell.dateLabel.textColor = [UIColor blackColor];
        cell.dateLabel.frame = cell.bounds;
        
    }
    else{
        
         cell.dateLabel.frame = CRM(0, 0, 26*PROPORTION_W, 26*PROPORTION_W);
        cell.dateLabel.layer.cornerRadius = 13*PROPORTION_W;
        cell.dateLabel.clipsToBounds = YES;
        cell.backgroundColor = [UIColor whiteColor];
        NSInteger firstDay = [self getFirstDayOfMonth:self.date];
        NSInteger allDays = [self numberOfMonthWithData:self.date];
        NSInteger nowDay = [self numberOfMonthToday];
        if (indexPath.row < firstDay) {
            cell.dateLabel.text = @"";
            cell.dateLabel.textColor = [UIColor blackColor];
            
        }else if (indexPath.row > allDays + firstDay - 1){
        cell.dateLabel.text  = @"";
//        cell.dateLabel.text = [NSString stringWithFormat:@"%ld",indexPath.row - allDays-firstDay + 1];
            cell.dateLabel.textColor = [UIColor grayColor];
        
        }
       else{
        NSInteger dayNumber = indexPath.row - firstDay + 1;
               cell.dateLabel.text = [NSString stringWithFormat:@"%ld",dayNumber];
               NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:self.date];
               components.day = dayNumber;
               NSDate *date = [[NSCalendar currentCalendar] dateFromComponents:components];
               BOOL isWeekend = [[NSCalendar currentCalendar] isDateInWeekend:date];
                if (_monthNumber == [self numberOfMonth]) {
                    cell.tag = 100 + indexPath.row;
               cell.dateLabel.textColor = [UIColor blackColor];
                    if (isWeekend) {
                        cell.dateLabel.textColor = [UIColor redColor];
                    }

               if (indexPath.row >= nowDay + firstDay ){
                   
                   cell.dateLabel.textColor = [UIColor grayColor];
                   if (isWeekend) {
                       cell.dateLabel.textColor = [UIColor colorWithRed:0.4168 green:0.0 blue:0.0043 alpha:1.0];
                   }

               }
                    if (indexPath == [changed.dic objectForKey:@"celll"]) {
                        cell.selected = YES;
                        NSCalendar *calender = [NSCalendar currentCalendar];
                        NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:self.date];
                        components.day = [cell.dateLabel.text integerValue];
                        _chooseDate = [calender dateFromComponents:components];
                        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
                        formatter.dateFormat = @"yyyy--MM--dd";
                        NSString *dateString = [formatter stringFromDate:_chooseDate];
                        _dateLabel.text = dateString;

                    }else{
                        
                        cell.selected = NO;
                    }

               if (indexPath.row == nowDay + firstDay - 1) {
                   cell.dateLabel.textColor = [UIColor greenColor];
//                   cell.selected = YES;
//                   Changed *changed = [Changed defaultSingleton];
//                   [changed.dic setObject:indexPath forKey:@"celll"];
               }
           }else if (_monthNumber<[self numberOfMonth]){
               cell.dateLabel.textColor = [UIColor grayColor];
               if (isWeekend) {
                   cell.dateLabel.textColor = [UIColor colorWithRed:0.4168 green:0.0 blue:0.0043 alpha:1.0];
               }

           
           }
           else{
               cell.dateLabel.textColor = [UIColor blackColor];
               if (indexPath == [changed.dic objectForKey:@"lastcelll"]) {
                   cell.selected = YES;
                   NSCalendar *calender = [NSCalendar currentCalendar];
                   NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:self.date];
                   components.day = [cell.dateLabel.text integerValue];
                   _chooseDate = [calender dateFromComponents:components];
                   NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
                   formatter.dateFormat = @"yyyy--MM--dd";
                   NSString *dateString = [formatter stringFromDate:_chooseDate];
                   _dateLabel.text = dateString;
                   
               }else{
                   
                   cell.selected = NO;
               }

               if (isWeekend) {
                   cell.dateLabel.textColor = [UIColor redColor];
               }
//               if (indexPath.row == nowDay + firstDay - 1) {
//                   cell.selected = YES;
//               }

           }
          
           
           }
    }
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
Changed *changed = [Changed defaultSingleton];
    YJCalenderCollectionViewCell *cell = (YJCalenderCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    if (_monthNumber==[self numberOfMonth]){
    [changed.dic setObject:indexPath forKey:@"celll"];
        [changed.dic removeObjectForKey:@"lastcelll"];
    }else{
    
    [changed.dic setObject:indexPath forKey:@"lastcelll"];
        [changed.dic removeObjectForKey:@"celll"];
    }
    
    NSCalendar *calender = [NSCalendar currentCalendar];
   NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:self.date];
    components.day = [cell.dateLabel.text integerValue];
    _chooseDate = [calender dateFromComponents:components];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"yyyy--MM--dd";
    NSString *dateString = [formatter stringFromDate:_chooseDate];
    _dateLabel.text = dateString;
    [_collectionView reloadData];
    
}
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{

    NSInteger nowDay = [self numberOfMonthToday];
    NSInteger firstDay = [self getFirstDayOfMonth:self.date];
   
    if (_monthNumber<[self numberOfMonth]) {
        return NO;
    }else if (indexPath.section == 0){
    
    return NO;
    }else if (indexPath.row >= nowDay + firstDay && _monthNumber == [self numberOfMonth]){
       
        return NO;
    }
    else{
        return YES;
    }
}


#pragma mark -- Getter

- (UILabel *)dateLabel {
    if (!_dateLabel) {
        _dateLabel = [[UILabel alloc]initWithFrame:CRM(0, 0, 110 * PROPORTION_W, 30*PROPORTION_H)];
        _dateLabel.center = CPM(CGRectGetMidX(self.bounds), 50 *PROPORTION_H);
        _dateLabel.textAlignment = NSTextAlignmentCenter;
        _dateLabel.backgroundColor = [UIColor yellowColor];
        for (int i = 0; i < 2; i ++) {
             UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
            if (i == 0) {
                [button setImage:[UIImage imageNamed:@"left"] forState:UIControlStateNormal];

            }else{
            
                [button setImage:[UIImage imageNamed:@"right"] forState:UIControlStateNormal];
            }
            button.frame = CRM(0 + 134 *PROPORTION_W * i, 7 *PROPORTION_H, 16 *PROPORTION_W, 16 *PROPORTION_W);
            button.center = CPM(CGRectGetMidX(self.bounds) - 60 *PROPORTION_W + 122 *PROPORTION_W *i, 50 *PROPORTION_H);
            button.tag = 20 + i;
            [button addTarget:self action:@selector(datebuttonTaped:) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:button];
        }
       
        
    }


    return _dateLabel;
}
- (UIButton *)deleteButton{
    if (!_deleteButton) {
         _deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _deleteButton.frame = CRM( 15 *PROPORTION_W , 5 *PROPORTION_H, 24 *PROPORTION_W, 24 *PROPORTION_W);
//        _deleteButton.center = CPM(CGRectGetMidX(self.bounds) - 60 *PROPORTION_W + 122 *PROPORTION_W , 50 *PROPORTION_H);
        [_deleteButton setImage:[UIImage imageNamed:@"叉叉"] forState:UIControlStateNormal];
//        [_deleteButton addTarget:self action:@selector(datebuttonTaped:) forControlEvents:UIControlEventTouchUpInside];
//        [self addSubview:_deleteButton];
    }

    return _deleteButton;
}

- (UIButton *)soureButton{
    if (!_soureButton) {
        _soureButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _soureButton.frame = CRM(CGRectGetWidth(self.bounds) - 39 *PROPORTION_W , 5 *PROPORTION_H, 24 *PROPORTION_W, 24 *PROPORTION_W);
        //        _deleteButton.center = CPM(CGRectGetMidX(self.bounds) - 60 *PROPORTION_W + 122 *PROPORTION_W , 50 *PROPORTION_H);
        [_soureButton setImage:[UIImage imageNamed:@"画下"] forState:UIControlStateNormal];
        //        [_deleteButton addTarget:self action:@selector(datebuttonTaped:) forControlEvents:UIControlEventTouchUpInside];
        //        [self addSubview:_deleteButton];
    }
    
    return _soureButton;
}

- (UISwipeGestureRecognizer *)leftSwipeGesture{
    
    if (!_leftSwipeGesture) {
        _leftSwipeGesture = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(action_leftGesture)];
        _leftSwipeGesture.direction = UISwipeGestureRecognizerDirectionLeft;
    }

    return _leftSwipeGesture;
}

- (UISwipeGestureRecognizer *)rightSwipeGesture{
    
    if (!_rightSwipeGesture) {
        _rightSwipeGesture = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(action_rightGesture)];
        _rightSwipeGesture.direction = UISwipeGestureRecognizerDirectionRight;
    }
    
    return _rightSwipeGesture;
}

- (void)action_leftGesture{
[UIView transitionWithView:self duration:0.5 options:UIViewAnimationOptionCurveEaseInOut animations:^{
    self.date = [self nextMonth:self.date];
} completion:^(BOOL finished) {
    
}];
    
}
- (void)action_rightGesture{
    [UIView transitionWithView:self duration:0.5 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.date = [self lastMonth:self.date];
    } completion:^(BOOL finished) {
        
    }];
    

}


- (void)setDate:(NSDate *)date{
    _date = date;
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat =@"yyyy--MM--dd";
    NSString *string = [formatter stringFromDate:date];
    self.dateLabel.text = string;
    [self.collectionView reloadData];


}

- (UICollectionView *)collectionView{
    
    if (!_collectionView) {
        
        //collectionView
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        layout.itemSize = CGSizeMake(CGRectGetWidth(self.bounds)/7.0,(CGRectGetHeight(self.bounds) - 70)/7.0);
        
        _collectionView = [[UICollectionView alloc]initWithFrame:CRM(0, 70  ,CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds) - 70) collectionViewLayout:layout];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        
        [_collectionView registerClass:[YJCalenderCollectionViewCell class] forCellWithReuseIdentifier:@"YJcell"];
        
    }
    

    return _collectionView;
}

- (void)datebuttonTaped:(UIButton *)sender{
   
    switch (sender.tag - 20) {
        case 1:
            [self action_leftGesture];
            break;
            
        default:
            [self action_rightGesture];
            break;
    }

}
@end












